package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AddFriendEntity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.GroupMemberAdpter;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/1/9.
 */
public class GroupDetailsActivity extends BaseSwipeBackActivity implements GroupMemberAdpter.GroupMemberListClickListener {

    private static final int RESULT_CODE = 1001 ;
    private static final int RESULT_CODE_ANSWER1 = 1002 ;
    private static final int RESULT_CODE_ANSWER2 = 1003 ;

    private static final String TAG = GroupDetailsActivity.class.getSimpleName();
    @BindView(R.id.group_member)
    RecyclerView groupMember;
    @BindView(R.id.apply_add)
    Button apply_add;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.pre_v_back)
    ImageView pre_v_back;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.per_more)
    LinearLayout per_more;

    private GroupMemberAdpter mGroupMemberAdpter;
    private PGService mPGservice;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();
    ImGroupEntivity mImGroupEntivity;
    private long groupid;
    private boolean isMember = false;
    private int type;

    private AlertDialog payDialog;
    PasswordEditText payPSD;

    @Override
    public int getContentViewId() {
        return R.layout.activity_group_details;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.group_details);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();

        groupMember.setLayoutManager(new LinearLayoutManager(this, OrientationHelper.HORIZONTAL, false));
        mGroupMemberAdpter = new GroupMemberAdpter(this);
//        mGroupMemberAdpter.setItemClickListener(this);
        groupMember.setAdapter(mGroupMemberAdpter);
        groupMember.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        mImGroupEntivity = (ImGroupEntivity) getIntent().getSerializableExtra("groupSeri");
        groupid = getIntent().getLongExtra("groupid", 0);
        type = getIntent().getIntExtra("type", 0);
        mImGroupEntivity.setId(groupid);
        if (type==11){
            doAddGroupToNative(getIntent().getLongExtra("id",0)+"");
        }
        if (null != mImGroupEntivity) {
            getGroupMember("" + mImGroupEntivity.getId());
            GlideUtils.loadCircleImage(getApplicationContext(), mImGroupEntivity.getHeadUrl(), image);
            name.setText(mImGroupEntivity.getName());
        }
    }

    @Override
    public void onGroupMemberListClick(View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putLong("id", mFriendEntivities.get(position).getId());
        bundle.putInt("type", 0);
        startActivity(FriendDetailActivity.class);
    }


/*
根据后台推送过来的消息通过消息，群员刷新
 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void RefreshingFriendPass(EventBusTypeData event) {
        switch (event.getType()) {
            case EventBusType.GROUP_APPLY_GRPOUP_REFRENSH_Y:
                mImGroupEntivity = (ImGroupEntivity) getIntent().getSerializableExtra("groupSeri");
                groupid = getIntent().getLongExtra("groupid", 0);
                type = getIntent().getIntExtra("type", 0);
                mImGroupEntivity.setId(groupid);
                if (type==11){
                    doAddGroupToNative(getIntent().getLongExtra("id",0)+"");
                }
                if (null != mImGroupEntivity) {
                    getGroupMember("" + mImGroupEntivity.getId());
                    GlideUtils.loadCircleImage(getApplicationContext(), mImGroupEntivity.getHeadUrl(), image);
                    name.setText(mImGroupEntivity.getName());
                }
        break;
            }
        }

    /**
     * 查询群组好友列表
     */
    private void getGroupMember(String groupId) {
        showProgress(null);
        mPGservice.getGroupMember(groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(SearchUserEntity friendEntivity) {

                mFriendEntivities = new ArrayList<>();
                List<ImFriendEntivity> info = friendEntivity.getInfo();
                if (null != info) {
                    String userId = ToolsUtils.getMyUserId();
                    int size = info.size();
                    for (int i = 0; i < size; i++) {
                        if (info.get(i).getId().toString().equals(userId)) {
                            isMember = true;
                        }
                    }

                    if (size < 6) {
                        mFriendEntivities = info;
                    } else {
                        for (int i = 0; i < size; i++) {
                            if (i < 6) {
                                mFriendEntivities.add(info.get(i));
                            } else {
                                break;
                            }
                        }
                    }
                }
                mGroupMemberAdpter.refresh(mFriendEntivities);
                if (isMember) {
                    apply_add.setText(getString(R.string.send_message));
                } else {
                    if (null != mImGroupEntivity){
                        String joinStatus = mImGroupEntivity.getJoinStatus();
                        int status = 0;
                        try {
                            status = Integer.parseInt(joinStatus);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        switch (status){
                            case 0 :
//                                requestFriend("", "" + mImGroupEntivity.getId());
                                apply_add.setText(getString(R.string.group_details_apply_add));
                                break;
                            case 1 :
                                apply_add.setText("加入该群需要身份验证！");
                                break;
                            case 2 :
                                apply_add.setText("加入该群需要回答问题并由管理员审核！");
                                break;
                            case 3 :
                                apply_add.setText("加入该群需要正确回答问题！");
                                break;
                            case 4 :
                                apply_add.setText("该群只能通过群成员邀请进群！");
                                break;
                            case 5 :
                                apply_add.setText("该群不允许任何人加入！");
                                break;
                            case 6 :
                                apply_add.setText(String.format("加入该群需要付费%s元共%s天！",mImGroupEntivity.getFee(),mImGroupEntivity.getDays()));
                                break;
                        }

                    }
//                    apply_add.setText(getString(R.string.group_details_apply_add));
                }
                hideProgress();
            }
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                //Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 申请加群
     * @param groupId
     */
    private void requestFriend(final String answer, final String groupId) {
        //Log.e(TAG, "requestFriend:  走到这里没????");
        showProgress(null);
        mPGservice.requestGroupJoin(answer, groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity addFriendEntity) {

                if (null != mImGroupEntivity){
                    String joinStatus = mImGroupEntivity.getJoinStatus();
                    int status = 0;
                    try {
                        status = Integer.parseInt(joinStatus);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    switch (status){
                        case 0 :
                            doAddGroupToNative(groupId);
                            showToast(getString(R.string.injoin_success));
                            break;
                        case 1 :
                            showToast("申请成功！");
                            break;
                        case 2 :
                            showToast("申请成功！");
                            break;
                        case 3 :
                            doAddGroupToNative(groupId);
                            showToast(getString(R.string.injoin_success));
                            break;
                        case 4 :
                            showToast("该群只能通过群成员邀请进群！");
                            break;
                        case 5 :
                            showToast("该群不允许任何人加入！");
                            break;
                        case 6 :
                            doAddGroupToNative(groupId);
                            showToast(getString(R.string.injoin_success));
                            break;
                    }
                }

                hideProgress();

                Log.e(TAG, "onNext: --------" + addFriendEntity.getInfo());

//                ImGroupEntivity friendEntivity = new ImGroupEntivity();
//                ReadyEntivity mReadyEntivity = IMSharedPreferences.getsaveReadyEntivity();
//                if (null != mReadyEntivity) {
//                    List<ImGroupEntivity> imGroupEntivities = mReadyEntivity.getGroupsInfo();
//                    if (!ToolsUtils.isMyGroupForId(friendEntivity.getId())) {
//                        imGroupEntivities.add(friendEntivity);
//                    }
//                }
//                scrollToFinishActivity();
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.e("info", "--001ex.getDisplayMessage()-- 不知道是不是这里错了？" + ex.getDisplayMessage());
                switch (ex.getCode()){
                    case -1 :
                        showToast("验证消息不能为空！");
                        break;
                    case -2 :
                        showToast("加群问题答案不正确！");
                        break;
                    case -3 :
                        showToast("不允许加入！");
                        break;
                    case -4 :
                        showToast("请先支付！");
                        break;
                    case -5 :
                        showToast("群人数已经达到上限！");
                        break;
                }
                hideProgress();
            }
        });
    }

    /**
     * 申请加群
     * @param groupId
     */
    private void payForGroupJoin(final String psw, final String groupId) {
        //Log.e(TAG, "requestFriend:  走到这里没????");
        showProgress(null);
        mPGservice.payForGroupJoin(MD5.MD532(psw), groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity addFriendEntity) {

                doAddGroupToNative(groupId);
                showToast(getString(R.string.injoin_success));
                hideProgress();

                Log.e(TAG, "onNext: --------" + addFriendEntity.getInfo());
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.e("info", "--001ex.getDisplayMessage()-- 不知道是不是这里错了？" + ex.getDisplayMessage());
                switch (ex.getCode()){

                    case 3:
                        showToast("余额不足");
                        break;
                    case 2 :
                        showToast("支付密码不正确！");
                        break;
                    case -1 :
//                        showToast("验证消息不能为空！");
                        showToast(ex.getDisplayMessage());
                        break;
                    case -2 :
                        showToast("加群问题答案不正确！");
                        break;
                    case -3 :
                        showToast("不允许加入！");
                        break;
                    case -4 :
                        showToast("请先支付！");
                        break;
                    case -5 :
                        showToast("群人数已经达到上限！");
                        break;
                }
                hideProgress();
            }
        });
    }

    /**
     * 因为添加好友的请求接口，返回数据不一致
     * 所以需要通过Id获取一遍，再添加
     */
    private void doAddGroupToNative(String groupId) {
        final String userId = ToolsUtils.getMyUserId();
        mPGservice.getGroupById(groupId, userId).subscribe(new AbsAPICallback<ImGroupEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
               // Log.e(TAG, "onResultError:  获取失败咯！！！");
                showToast(getString(R.string.net_visit_exception));
            }
            @Override
            public void onNext(ImGroupEntivity imGroupEntivity) {
                Log.i("info", "onNext: =============================="+new Gson().toJson(imGroupEntivity));
                imGroupEntivity.setCurrentid(Long.valueOf(userId));
                imGroupEntivity.setReceiveTip(1);
                imGroupEntivity.save();
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                apply_add.setText(getString(R.string.send_message));
                isMember = true;
            }
        });
    }

    @OnClick({R.id.apply_add, R.id.pre_v_back, R.id.per_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.apply_add:
                if (!isMember) {
                    if (null != mImGroupEntivity){
                        String joinStatus = mImGroupEntivity.getJoinStatus();
                        String ds=mImGroupEntivity.getQuestion();
                        int status = 0;
                        try {
                            status = Integer.parseInt(joinStatus);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        switch (status){
                            case 0 :
                                requestFriend("", "" + mImGroupEntivity.getId());
                                break;
                            case 1 :
                                AddGroupSetQuestActivity.start(GroupDetailsActivity.this, 3, RESULT_CODE);
                                break;
                            case 2 :
                                AddGroupSetQuestActivity.start(GroupDetailsActivity.this, 4, RESULT_CODE_ANSWER1, mImGroupEntivity.getQuestion(), "");
                                break;
                            case 3 :
                                AddGroupSetQuestActivity.start(GroupDetailsActivity.this, 4, RESULT_CODE_ANSWER2, mImGroupEntivity.getQuestion(), "");
                                break;
                            case 4 :
                                showToast("该群只能通过群成员邀请进群！");
                                break;
                            case 5 :
                                showToast("该群不允许任何人加入！");
                                break;
                            case 6 :
                                final UserEntivity user = ToolsUtils.getUser();
                                if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                                    //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                                    showSetPSWdialog();
                                    return;
                                }
                                showPayDialog();
                                break;
                        }

                    }

                } else {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("groupSeri", mImGroupEntivity);
                    bundle.putLong("groupid", mImGroupEntivity.getId());
                    startActivity(ChatGroupActivity.class, bundle);
                }
                break;
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.per_more:
                Bundle bundle = new Bundle();
//                bundle.putSerializable("groupSeri", mImGroupEntivity);
                bundle.putString("groupId", mImGroupEntivity.getId()+"");
                startActivity(GroupUsersActivity.class, bundle);
                break;
        }
    }


    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(GroupDetailsActivity.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(GroupDetailsActivity.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        try {
            payDialog = new AlertDialog.Builder(this).setView(dialog).create();
            payDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }

        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payDialog.dismiss();
            }
        });
        payCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
//                    dopaymoney(pwd,imMessage.getDestid());
                    payForGroupJoin(pwd, "" + mImGroupEntivity.getId());
//                    payForGroupJoin
                    //  validatePayPwd(pwd);
                    payDialog.dismiss();
                }
            }
        });
    }

    private void popupKeyboard(final PasswordEditText editText) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case RESULT_CODE :
                if (resultCode == RESULT_OK){
                    String yzinfo = data.getStringExtra("yzinfo");
                    if (null==yzinfo|| TextUtils.isEmpty(yzinfo)){
                        showToast("请输入验证信息！");
                    }else {
                        requestFriend(yzinfo, "" + mImGroupEntivity.getId());
                    }
                }
                break;
            case RESULT_CODE_ANSWER1 :
                if (resultCode == RESULT_OK){
                    String result = data.getStringExtra("result");
                    if (null==result|| TextUtils.isEmpty(result)){
                        showToast("请输入答案！");
                    }else {
                        requestFriend(result, "" + mImGroupEntivity.getId());
                    }
                }
                break;
            case RESULT_CODE_ANSWER2 :
                if (resultCode == RESULT_OK){
                    String answer = data.getStringExtra("result");
                    if (null==answer|| TextUtils.isEmpty(answer)){
                        showToast("请输入答案！");
                    }else {
                        requestFriend(answer, "" + mImGroupEntivity.getId());
                    }
                }
                break;
        }


    }
}
